package com.example.mq.server.datacenter;

import com.example.mq.common.MqException;
import com.example.mq.server.core.Binding;
import com.example.mq.server.core.Exchange;
import com.example.mq.server.core.MSGQueue;
import com.example.mq.server.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/*
* 通过这个类来管理磁盘上的数据
* 1.数据库中的 队列 绑定 交换机
* 2.数据文件上的消息
* 上层逻辑如果需要操作硬盘,都通过这个类来完成(上层代码无需关心数据是存储在数据库还是文件中)
* */
public class DiskDataCenter {
    private final DataBaseManager dataBaseManager = new DataBaseManager();
    private final MessageFileManager messageFileManager = new MessageFileManager();

    /**
     * 针对上述两个实例进行初始化工作
     */
    public void init(){
        dataBaseManager.init();
        messageFileManager.init();
    }

    // 封装交换机操作
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(Exchange exchange){
        dataBaseManager.deleteExchange(exchange.getName());
    }

    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }

    // 封装队列操作
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        // 创建队列时,不应只是简单的把队列信息写到数据库,还应该创建队列文件
        messageFileManager.createQueueFiles(queue.getName());
    }

    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        messageFileManager.destroyQueueFiles(queueName);
    }

    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueues();
    }

    // 封装绑定操作
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBindings();
    }


    // 封装消息操作
    public void sendMessage(MSGQueue queue, Message message) throws MqException, IOException {
        messageFileManager.sendMessage(queue,message);
    }

    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue,message);
        if(messageFileManager.checkGc(queue.getName())){
            messageFileManager.gc(queue);
        }
    }

    // 加载所有文件
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, ClassNotFoundException, MqException{
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
